#include <iostream>
#include <pthread.h>
#include <time.h>
#include <unistd.h>
#include "RingQueue.hpp"
#include "Task.hpp"

std::string oper = "+-*/%&!@()";
RingQueue<Task> *rq = new RingQueue<Task>();

void *Productor(void *args)
{
    LogMessage(Debug, "create Productor success");
    // RingQueue<Task> *rq = static_cast<RingQueue<Task> *>(args);
    std::string name = (char*)args;
    while (true)
    {
        // 构建任务
        int date1 = rand() % 100;
        usleep(123);
        int date2 = rand() % 100;
        usleep(321);
        char op = oper[rand() % oper.size()];
        Task t(date1, op, date2);

        // 将任务push到环形队列当中
        rq->Push(t);
        LogMessage(Debug, "%s create a task:  %d %c %d",name.c_str(), t._x, t._op, t._y);
        sleep(1);
    }
}

void *Consumer(void *args)
{
    LogMessage(Debug, "create Consumer success");
    // RingQueue<Task> *rq = static_cast<RingQueue<Task> *>(args);
    std::string name = (char*)args;
    while (true)
    {
        Task t;
        rq->Pop(&t);
        t.Run();
        LogMessage(Debug, "%s get a task:  result: %d, code: %d",name.c_str(),  t._result, t._code);

        // sleep(1);
    }
}

int main()
{
    srand((unsigned)time(nullptr));
    // RingQueue<Task> *rq = new RingQueue<Task>();
    pthread_t p[5];
    pthread_t c[5];
    for (int i = 0; i < 5; i++)
    {
        char buffer[1024];
        snprintf(buffer, sizeof(buffer), "Productor-%d", i + 1);
        pthread_create(&p[i], nullptr, Productor, (void *)buffer);
    }
    for (int i = 0; i < 5; i++)
    {
        char buffer[1024];
        snprintf(buffer, sizeof(buffer), "Consumer-%d", i + 1);
        pthread_create(&c[i], nullptr, Consumer, (void *)buffer);
    }

    for (int i = 0; i < 5; i++)
        pthread_join(p[i], nullptr);
    for (int i = 0; i < 5; i++)
        pthread_join(c[i], nullptr);

    return 0;
}